from django.core.management.base import BaseCommand
import os

class Command(BaseCommand):
    help = '扫描并显示目录的完整结构'

    def add_arguments(self, parser):
        parser.add_argument('directory', type=str, help='要扫描的目录路径')

    def handle(self, *args, **options):
        directory = options['directory']
        self.scan_directory(directory)

    def clean_name(self, name):
        # 移除序号前缀（如 "01_"）
        if '_' in name:
            parts = name.split('_', 1)
            if parts[0].isdigit():
                return parts[1]
        return name

    def scan_directory(self, start_path):
        self.stdout.write(self.style.SUCCESS(f'\n开始扫描目录: {start_path}\n'))
        
        # 用于存储所有目录的结构
        structure = []
        
        for root, dirs, files in os.walk(start_path):
            # 计算当前目录的相对路径层级
            level = root[len(start_path):].count(os.sep)
            indent = '  ' * level
            
            # 获取当前目录名
            current_dir = os.path.basename(root)
            if level > 0:  # 不显示起始目录
                self.stdout.write(f"{indent}[目录] {self.clean_name(current_dir)}")
            
            # 显示所有文件
            sub_indent = '  ' * (level + 1)
            md_files = [f for f in files if f.endswith('.md') and f != 'README.md']
            for f in sorted(md_files):
                clean_name = self.clean_name(f.replace('.md', ''))
                file_path = os.path.join(root, f)
                
                # 读取文件的第一行作为描述
                description = ''
                try:
                    with open(file_path, 'r', encoding='utf-8') as file:
                        first_line = file.readline().strip()
                        if first_line.startswith('#'):
                            description = first_line.lstrip('#').strip()
                        else:
                            description = first_line
                except Exception as e:
                    self.stdout.write(self.style.WARNING(f'读取文件失败: {str(e)}'))
                
                # 记录文件信息
                structure.append({
                    'type': 'file',
                    'name': clean_name,
                    'path': os.path.relpath(file_path, start_path),
                    'level': level + 1,
                    'description': description
                })
                
                self.stdout.write(f"{sub_indent}[文档] {clean_name}")
                if description:
                    self.stdout.write(f"{sub_indent}      描述: {description}")
            
            # 记录目录信息
            if level > 0:
                readme_path = os.path.join(root, 'README.md')
                description = ''
                if os.path.exists(readme_path):
                    try:
                        with open(readme_path, 'r', encoding='utf-8') as file:
                            first_line = file.readline().strip()
                            if first_line.startswith('#'):
                                description = first_line.lstrip('#').strip()
                            else:
                                description = first_line
                    except Exception as e:
                        self.stdout.write(self.style.WARNING(f'读取README失败: {str(e)}'))
                
                structure.append({
                    'type': 'directory',
                    'name': self.clean_name(current_dir),
                    'path': os.path.relpath(root, start_path),
                    'level': level,
                    'description': description
                })
        
        # 按层级排序并显示完整结构
        self.stdout.write(self.style.SUCCESS('\n完整的目录结构:'))
        sorted_structure = sorted(structure, key=lambda x: (x['path'], x['type']))
        for item in sorted_structure:
            indent = '  ' * item['level']
            type_str = '[目录]' if item['type'] == 'directory' else '[文档]'
            self.stdout.write(f"{indent}{type_str} {item['name']}")
            if item['description']:
                self.stdout.write(f"{indent}      描述: {item['description']}")
            self.stdout.write(f"{indent}      路径: {item['path']}") 